<?php
/**
 * Created by PhpStorm.
 * User: daimingkang
 * Date: 2018/12/24
 * Time: 10:48 PM
 */

namespace App\Api\Controllers\User;


use App\Api\Controllers\BaseController;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Models\User;
use App\Models\UserStoreSet;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SetController extends BaseController
{

    // 开启收款顺序
    public function pay_ways_open(Request $request)
    {
        try {
            $token = $this->parseToken(); //
            $is_open = $request->get('is_open', '');
            $store_id = $request->get('store_id', '');

            $store_pay_ways_open = 0;
            $store = Store::where('store_id', $store_id)->first();
            if ($store) {
                $store_pay_ways_open = $store->store_pay_ways_open;
            } else {
                $this->status = '2';
                $this->message = '没有找到该门店';
                return $this->format();
            }

            if ($is_open == '') {
                $this->status = '1';
                $this->message = '数据返回成功';
                $data = [
                    'store_pay_ways_open' => $store_pay_ways_open,
                ];
                return $this->format($data);
            } else {
                $store->update([
                    'store_pay_ways_open' => $is_open
                ]);
            }

        } catch (\Exception $exception) {
            $this->status = '0';
            $this->message = $exception->getMessage();
            return $this->format();
        }

        $this->status = '1';
        $this->message = '修改成功';
        $data = [
            'store_pay_ways_open' => $is_open,
        ];
        return $this->format($data);
    }

    //扣款顺序列表
    public function pay_ways_sort(Request $request){
        try {
            $user = $this->parseToken();//
            $store_id = $request->get('store_id', '');
            if ($store_id) {
                
                $alipay = DB::table('store_pay_ways')
                    ->where('store_id', $store_id)
                    ->where('ways_source', 'alipay')
                    ->select('id as store_pay_ways_id', "rate",'ways_desc', 'ways_type', 'store_id', 'sort', 'ways_source', 'company')
                    ->where('status', 1)
                    ->orderBy('store_pay_ways.sort', 'asc')
                    ->get();
                    
                    if(!empty($alipay)){
                        foreach ($alipay as $k=>$v){
                            $company_config = DB::table('company_config')
                                ->where('store_id', $v->store_id)
                                ->where('company', $v->company)
                                ->first();
                            if(empty($company_config)){
                                continue;
                            }
                            if($company_config->model=='1'){
                                $alipay[$k]->rate = $company_config->configure_channel_fee;
                                $model_desc='服务费模式';
                            }else if($company_config->model=='2'){
                                $alipay[$k]->rate = $v->rate;
                                $model_desc='代扣模式';
                            }else if($company_config->model=='3'){
                                $alipay[$k]->rate = $v->rate;
                                $model_desc='通道扣费';
                            }else if($company_config->model=='4'){
                                $alipay[$k]->rate = $company_config->configure_channel_fee;
                                $model_desc='预充模式';
                            }
                            $alipay[$k]->model_desc = $model_desc;
                        }
                    }
                    
                $weixin = DB::table('store_pay_ways')
                    ->where('store_id', $store_id)
                    ->where('ways_source', 'weixin')
                    ->select('id as store_pay_ways_id', "rate",'ways_desc', 'ways_type', 'store_id', 'sort', 'ways_source', 'company')
                    ->where('status', 1)
                    ->orderBy('store_pay_ways.sort', 'asc')
                    ->get();
                    
                    if(!empty($weixin)){
                        foreach ($weixin as $k=>$v){
                            $company_config = DB::table('company_config')
                                ->where('store_id', $v->store_id)
                                ->where('company', $v->company)
                                ->first();
                            if(empty($company_config)){
                                continue;
                            }
                            if($company_config->model=='1'){
                                $weixin[$k]->rate = $company_config->configure_channel_fee;
                                $model_desc='服务费模式';
                            }else if($company_config->model=='2'){
                                $weixin[$k]->rate = $v->rate;
                                $model_desc='代扣模式';
                            }else if($company_config->model=='3'){
                                $weixin[$k]->rate = $v->rate;
                                $model_desc='通道扣费';
                            }else if($company_config->model=='4'){
                                $weixin[$k]->rate = $company_config->configure_channel_fee;
                                $model_desc='预充模式';
                            }
                            $weixin[$k]->model_desc = $model_desc;
                        }
                    }
                    
                $jd = DB::table('store_pay_ways')
                    ->where('store_id', $store_id)
                    ->where('ways_source', 'jd')
                    ->select('id as store_pay_ways_id', "rate","rate_a",'ways_desc', 'ways_type', 'store_id', 'sort', 'ways_source', 'company')
                    ->where('status', 1)
                    ->orderBy('store_pay_ways.sort', 'asc')
                    ->get();
                    
                    if(!empty($jd)){
                        foreach ($jd as $k=>$v){
                            $company_config = DB::table('company_config')
                                ->where('store_id', $v->store_id)
                                ->where('company', $v->company)
                                ->first();
                            if(empty($company_config)){
                                continue;
                            }
                            if($company_config->model=='1'){
                                $jd[$k]->rate = $company_config->configure_channel_fee;
                                $model_desc='服务费模式';
                            }else if($company_config->model=='2'){
                                $jd[$k]->rate = $v->rate;
                                $model_desc='代扣模式';
                            }else if($company_config->model=='3'){
                                $jd[$k]->rate = $v->rate_a;
                                $model_desc='通道扣费';
                            }else if($company_config->model=='4'){
                                $jd[$k]->rate = $company_config->configure_channel_fee;
                                $model_desc='预充模式';
                            }
                            $jd[$k]->model_desc = $model_desc;
                        }
                    }
                    
                $unionpay = DB::table('store_pay_ways')
                    ->where('store_id', $store_id)
                    ->where('ways_source', 'unionpay')
                    ->select('id as store_pay_ways_id',"rate","rate_a", 'ways_desc', 'ways_type', 'store_id', 'sort', 'ways_source', 'company')
                    ->where('status', 1)
                    ->orderBy('store_pay_ways.sort', 'asc')
                    ->get();
                    
                    if(!empty($unionpay)){
                        foreach ($unionpay as $k=>$v){
                            $company_config = DB::table('company_config')
                                ->where('store_id', $v->store_id)
                                ->where('company', $v->company)
                                ->first();
                            if(empty($company_config)){
                                continue;
                            }
                            if($company_config->model=='1'){
                                $unionpay[$k]->rate = $company_config->configure_channel_fee;
                                $model_desc='服务费模式';
                            }else if($company_config->model=='2'){
                                $unionpay[$k]->rate = $v->rate;
                                $model_desc='代扣模式';
                            }else if($company_config->model=='3'){
                                $unionpay[$k]->rate = $v->rate_a;
                                $model_desc='通道扣费';
                            }else if($company_config->model=='4'){
                                $unionpay[$k]->rate = $company_config->configure_channel_fee;
                                $model_desc='预充模式';
                            }
                            $unionpay[$k]->model_desc = $model_desc;
                            unset($unionpay[$k]->rate_a);
                        }
                    }
                    
                $wing = DB::table('store_pay_ways')
                    ->where('store_id', $store_id)
                    ->where('ways_source', 'Bestpay')
                    ->select('id as store_pay_ways_id', "rate","rate_a",'ways_desc', 'ways_type', 'store_id', 'sort', 'ways_source', 'company')
                    ->where('status', 1)
                    ->orderBy('store_pay_ways.sort', 'asc')
                    ->get();
                    
                    if(!empty($wing)){
                        foreach ($wing as $k=>$v){
                            $company_config = DB::table('company_config')
                                ->where('store_id', $v->store_id)
                                ->where('company', $v->company)
                                ->first();
                            if(empty($company_config)){
                                continue;
                            }
                            if($company_config->model=='1'){
                                $wing[$k]->rate = $company_config->configure_channel_fee;
                                $model_desc='服务费模式';
                            }else if($company_config->model=='2'){
                                $wing[$k]->rate = $v->rate;
                                $model_desc='代扣模式';
                            }else if($company_config->model=='3'){
                                $wing[$k]->rate = $v->rate_a;
                                $model_desc='通道扣费';
                            }else if($company_config->model=='4'){
                                $wing[$k]->rate = $company_config->configure_channel_fee;
                                $model_desc='预充模式';
                            }
                            $wing[$k]->model_desc = $model_desc;
                        }
                    }
                    

                return json_encode(['status' => 1, 'is_open' => 1, 'message' => '数据返回成功', 
                    'data' => [
                        'ailpay' => $alipay,
                        'weixin' => $weixin,
                        'jd' => $jd,
                        'unionpay' => $unionpay,
                        'Bestpay' => $wing,
                    ]
                ]);

            } else {
                return json_encode(['status' => 2, 'message' => '门店ID必须传']);
            }

        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage().$exception->getLine().$exception->getFile()]);
        }
    }


    //扣款顺序初始化
    public function pay_ways_sort_start(Request $request)
    {
        try {
            $user = $this->parseToken();//
            $store_id = $request->get('store_id', '');
            $StorePayWay = StorePayWay::where('store_id', $store_id)
                ->where('status', 1)
                ->select('ways_source', 'sort', 'id')
                ->get();

            $a = 0;
            $b = 0;
            $c = 0;
            $d = 0;


            $user = User::where('id', $user->user_id)->first();
            $hasPermission = $user->hasPermissionTo('通道初始化');

            if (!$hasPermission) {
                return json_encode(['status' => 2, 'message' => '没有权限']);
            }

            foreach ($StorePayWay as $k => $v) {
                //支付宝
                if ($v['ways_source'] == "alipay") {
                    $a = $a + 1;
                    StorePayWay::where('id', $v->id)->update(['sort' => $a]);
                }
                //微信
                if ($v['ways_source'] == "weixin") {
                    $b = $b + 1;
                    StorePayWay::where('id', $v->id)->update(['sort' => $b]);


                }

                //jd
                if ($v['ways_source'] == "jd") {

                    $c = $c + 1;
                    StorePayWay::where('id', $v->id)->update(['sort' => $c]);

                }

                //unionpay
                if ($v['ways_source'] == "unionpay") {
                    $d = $d + 1;
                    StorePayWay::where('id', $v->id)->update(['sort' => $d]);
                }

            }

            return json_encode(['status' => 1, 'message' => '初始化成功']);


        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }
    
    //扣款顺序修改
    public function pay_ways_sort_edit_pc(Request $request)
    {
        try {
            $user = $this->parseToken();//
            $store_pay_ways_id = (int)$request->get('store_pay_ways_id');
            $store_id = $request->get('store_id');
            $new_sort = $request->get('new_sort');
            $check_data = [
                'store_pay_ways_id' => '通道类型id',
                'new_sort' => '新位置',
            ];

            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            $user = User::where('id', $user->user_id)->first();
            $hasPermission = $user->hasPermissionTo('收款顺序修改');

            if (!$hasPermission) {
                return json_encode(['status' => 2, 'message' => '没有权限']);
            }

            $ch_storePayWay = StorePayWay::where('id', $store_pay_ways_id)->first();

            $store_id = $ch_storePayWay->store_id;
            $ways_source = $ch_storePayWay->ways_source;
            $sort = $ch_storePayWay->sort;//旧的位置

            if ((int)$sort == (int)$new_sort) {
                return json_encode(['status' => 2, 'message' => '位置没有任何改动']);
            }
            
            
            
            $pash = $request->path();
            $pass = $request->get('pass', '');
            $pass = substr(base64_decode($pass), 0, -5);
            
            $pass_verify = $this->pass_verify($pass, $pash); // 密钥验证
            $pass_verify = json_decode($pass_verify, true);
            // print_r( $pash );die;
            if( $pass_verify['status'] == '1'){
                $pass_id = DB::table('pass')->where(['pass' => $pass])->value('id'); // 密钥id
                $remark = '门店修改收款顺序: 门店id: ' . $store_id . '修改收款顺序';
                $this->operation_log( $this->parseToken()->user_id, 7, $remark , $pass_id );
            }else{
                return json_encode(['status' => 2, 'message' => '权限不足', 'data' => []]);
            }
            // print_r( 2 );die;
            
            

            $old_StorePayWay = StorePayWay::where('sort', $new_sort)
                ->where('store_id', $store_id)
                ->where('ways_source', $ways_source)
                ->first();

            if ($old_StorePayWay) {
                //开启事务
                try {
                    DB::beginTransaction();

                //先零时配置一个
                $old_StorePayWay->update([
                    'sort' => time(),
                ]);

                $ch_storePayWay->update([
                    'sort' => $new_sort,
                ]);
                $ch_storePayWay->save();
                $old_StorePayWay->save();


                //修正
                $old_StorePayWay->update([
                    'sort' => $sort,
                ]);
                $old_StorePayWay->save();

                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    return json_encode(['status' => 2, 'message' => $e->getMessage()]);
                }
            } else {
                $ch_storePayWay->update([
                    'sort' => $new_sort,
                ]);
                $ch_storePayWay->save();
            }
        } catch (\Exception $exception) {
            return json_encode(['status' => 0, 'message' => $exception->getMessage()]);
        }

        $this->status = '1';
        $this->message = '顺序修改成功';
        return $this->format();
    }

    //扣款顺序修改
    public function pay_ways_sort_edit(Request $request)
    {
        try {
            $user = $this->parseToken();//
            $store_pay_ways_id = (int)$request->get('store_pay_ways_id');
            $store_id = $request->get('store_id');
            $new_sort = $request->get('new_sort');
            $check_data = [
                'store_pay_ways_id' => '通道类型id',
                'new_sort' => '新位置',
            ];

            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            $user = User::where('id', $user->user_id)->first();
            $hasPermission = $user->hasPermissionTo('收款顺序修改');

            if (!$hasPermission) {
                return json_encode(['status' => 2, 'message' => '没有权限']);
            }

            $ch_storePayWay = StorePayWay::where('id', $store_pay_ways_id)->first();

            $store_id = $ch_storePayWay->store_id;
            $ways_source = $ch_storePayWay->ways_source;
            $sort = $ch_storePayWay->sort;//旧的位置

            if ((int)$sort == (int)$new_sort) {
                return json_encode(['status' => 2, 'message' => '位置没有任何改动']);
            }
            
            
            
            // $pash = $request->path();
            // $pass = $request->get('pass', '');
            // $pass = substr(base64_decode($pass), 0, -5);
            
            // $pass_verify = $this->pass_verify($pass, $pash); // 密钥验证
            // $pass_verify = json_decode($pass_verify, true);
            // // print_r( $pash );die;
            // if( $pass_verify['status'] == '1'){
            //     $pass_id = DB::table('pass')->where(['pass' => $pass])->value('id'); // 密钥id
            //     $remark = '门店修改收款顺序: 门店id: ' . $store_id . '修改收款顺序';
            //     $this->operation_log( $this->parseToken()->user_id, 7, $remark , $pass_id );
            // }else{
            //     return json_encode(['status' => 2, 'message' => '权限不足', 'data' => []]);
            // }
            
            
            

            $old_StorePayWay = StorePayWay::where('sort', $new_sort)
                ->where('store_id', $store_id)
                ->where('ways_source', $ways_source)
                ->first();

            if ($old_StorePayWay) {
                //开启事务
                try {
                    DB::beginTransaction();

                //先零时配置一个
                $old_StorePayWay->update([
                    'sort' => time(),
                ]);

                $ch_storePayWay->update([
                    'sort' => $new_sort,
                ]);
                $ch_storePayWay->save();
                $old_StorePayWay->save();


                //修正
                $old_StorePayWay->update([
                    'sort' => $sort,
                ]);
                $old_StorePayWay->save();

                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    return json_encode(['status' => 2, 'message' => $e->getMessage()]);
                }
            } else {
                $ch_storePayWay->update([
                    'sort' => $new_sort,
                ]);
                $ch_storePayWay->save();
            }
        } catch (\Exception $exception) {
            return json_encode(['status' => 0, 'message' => $exception->getMessage()]);
        }

        $this->status = '1';
        $this->message = '顺序修改成功';
        return $this->format();
    }


    //收款方式置顶
    public function pay_ways_sort_top(Request $request)
    {

        try {
            $token_info = $this->parseToken();
            $store_ids = $request->get('store_ids', '[]'); //需要修改的门店数组
            $ways_type = $request->get('ways_type', ''); //需要修改的支付方式

            $user = User::where('id', $token_info->user_id)->first();
            $user->hasPermissionTo('批量收款顺序置顶');  //判断是否有权限

            if ($user->level != 0) {
                $this->status = '2';
                $this->message = '您不是平台账户，无权操作';
                return $this->format();
            }

            $check_data = [
                'store_ids' => '门店id集',
                'ways_type' => '收款方式',
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                $this->status = '2';
                $this->message = $check;
                return $this->format();
            }

            if ($store_ids == '[]') {
                $this->status = '2';
                $this->message = '门店信息为空';
                return $this->format();
            }
            $store_id_arr = array_column(json_decode($store_ids, true), 'store_id');

            if ($store_id_arr && is_array($store_id_arr)) {
                foreach ($store_id_arr as $store_id) {
                    $store_pay_way_obj = StorePayWay::where('store_id', $store_id)
                        ->where('ways_type', $ways_type)
                        ->where('status', 1)
                        ->where('is_close', 0)
                        ->orderBy('updated_at', 'desc')
                        ->first();
                    if (!$store_pay_way_obj) {
                        continue;
                    }

                    $sort = $store_pay_way_obj->sort; //旧的位置
                    $ways_source = $store_pay_way_obj->ways_source; //旧的支付类型

                    //已经置顶的跳过
                    if ((int)$sort == 1) {
                        continue;
                    }

                    //同支付类型，只能有一个置顶
                    $min_ways_source = StorePayWay::where('store_id', $store_id)
                        ->where('ways_source', $ways_source)
                        ->where('sort', 1)
                        ->where('status', 1)
                        ->where('is_close', 0)
                        ->orderBy('updated_at', 'desc')
                        ->first();
                    if ($min_ways_source) {
                        //开启事务
                        try {
                            DB::beginTransaction();

                            //将原有置顶排序减一
                            $min_ways_source->update([
                                'sort' => 2,
                            ]);
                            $min_ways_source->save();

                            $store_pay_way_obj->update([
                                'sort' => 1,
                            ]);
                            $store_pay_way_obj->save();

                            DB::commit();
                        } catch (\Exception $ex) {
                            DB::rollBack();
                            $this->status = '2';
                            $this->message = $ex->getMessage();
                            return $this->format();
                        }
                    } else {
                        $store_pay_way_obj->update([
                            'sort' => 1,
                        ]);
                        $store_pay_way_obj->save();
                    }
                }

            } else {
                $this->status = '2';
                $this->message = '门店信息不能为空';
                return $this->format();
            }

        } catch (\Exception $exception) {
            $this->status = '0';
            $this->message = $exception->getMessage();
            return $this->format();
        }

        $this->status = '1';
        $this->message = '收款方式置顶成功';
        return $this->format();
    }


    //查看是否需要审核商户
    public function user_store_set_status(Request $request)
    {
        try {
            $user = $this->parseToken();//
            $user_id = $request->get('user_id', '');
            $status_check = $request->get('status_check', '');
            $admin_status_check = $request->get('admin_status_check', '');

            if ($user_id == "") {
                return json_encode(['status' => 2, 'message' => 'user_id必须传']);
            }

            $UserStoreSet = UserStoreSet::where('user_id', $user_id)->first();

            //查看
            if ($status_check == "") {
                if ($UserStoreSet) {
                    return json_encode([
                        'status' => 1,
                        'data' => $UserStoreSet
                    ]);
                } else {
                    return json_encode([
                        'status' => 1,
                        'data' => [
                            'user_id' => $user_id,
                            'status_check' => 0,
                            'admin_status_check' => 0,
                        ]
                    ]);
                }
            }

            $data = [
                'user_id' => $user_id,
                'status_check' => $status_check,
                'admin_status_check' => $admin_status_check,
            ];

            if ($UserStoreSet) {
                $UserStoreSet->update($data);
                $UserStoreSet->save();
            } else {
                UserStoreSet::create($data);
            }


            return json_encode(['status' => 1, 'message' => '修改成功']);


        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }


    public function store_ways_set(Request $request)
    {
        try {
            $user = $this->parseToken();//
            $store_id = $request->get('store_id', '');
            $is_close = $request->get('is_close', '');
            $pcredit = $request->get('pcredit', '');
            $credit = $request->get('credit', '');
            $ways_type = $request->get('ways_type', '');
            $company = $request->get('company', '');
            $pay_amount_e = $request->get('pay_amount_e', '');

            $check_data = [
                'store_id' => 'store_id',
                'is_close' => 'is_close',
                'pcredit' => 'pcredit',
                "credit" => 'credit',
                "ways_type" => 'ways_type',
                "company" => 'company',
                "pay_amount_e" => 'pay_amount_e',

            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            if ($user->pid) {
                $user = User::where('id', $user->user_id)->first();
                $hasPermission = $user->hasPermissionTo('通道禁用');
                if (!$hasPermission) {
                    return json_encode(['status' => 2, 'message' => '没有权限']);
                }
            }

            $StorePayWay = StorePayWay::where('store_id', $store_id)
                ->where('ways_type', $ways_type)
                ->where('company', $company)
                ->first();
            if ($StorePayWay) {
                $StorePayWay->update([
                    'is_close' => $is_close,
                    'pcredit' => $pcredit,
                    "credit" => $credit,
                    "ways_type" => $ways_type,
                    "company" => $company,
                    "pay_amount_e" => $pay_amount_e
                ]);
                $StorePayWay->save();
            } else {
                return json_encode([
                    'status' => 2,
                    'message' => '通道未开通无法设置'
                ]);
            }

            return json_encode([
                'status' => 1,
                'message' => '修改成功',
                'data' => $request->except(['token'])
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => 0,
                'message' => $exception->getMessage()
            ]);
        }
    }

    public function store_ways_select(Request $request)
    {
        try {
            $user = $this->parseToken();//
            $store_id = $request->get('store_id', '');
            $ways_type = $request->get('ways_type', '');
            $company = $request->get('company', '');


            $check_data = [
                'store_id' => 'store_id',
                "ways_type" => 'ways_type',
                "company" => 'company',

            ];

            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }


            $data = StorePayWay::where('store_id', $store_id)
                ->where('ways_type', $ways_type)
                ->where('company', $company)
                ->select(
                    'pcredit',
                    'credit',
                    'is_close',
                    'company',
                    'ways_type',
                    'pay_amount_e'
                )
                ->first();
            if ($data) {
                $data = [
                    'pcredit' => $data->pcredit,
                    'credit' => $data->credit,
                    'is_close' => $data->is_close,
                    'company' => $data->company,
                    'ways_type' => $data->ways_type,
                    'pay_amount_e' => $data->pay_amount_e,


                ];
            } else {
                $data = [
                    'pcredit' => '01',
                    'credit' => '01',
                    'is_close' => '0',
                    'company' => $company,
                    'ways_type' => $ways_type,
                    'pay_amount_e' => '50000',
                ];
            }

            return json_encode(['status' => 1, 'message' => '查询成功', 'data' => $data]);


        } catch (\Exception $exception) {

            return json_encode(['status' => 0, 'message' => $exception->getMessage()]);
        }

    }


}
